<?php
/**
 * Manuscript Comparator
 * Copyright (C) 2009  OpenScriptures.org
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @todo Add persistant position of unchecked MSS via cookie
 * @todo Add a "please wait" notice upon submission of form
 */

ini_set('memory_limit', '40M');
$startTime = microtime(true);
define("MAX_TOKENS", 21000);

if(strpos(@$_SERVER['HTTP_ACCEPT'], 'xhtml') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false)
	header('content-type: application/xhtml+xml; charset=utf-8');
else
	header('content-type: text/html; charset=utf-8');

require_once('../reference-parser.lib.php');
require_once('../svn.lib.php');

/**
 * Load JSON encoding in case it is not natively available
 */
if(!function_exists('json_encode')){
	require_once '../JSON.php';
    function json_encode($data) {
		static $json;
		if(!isset($json))
			$json = new Services_JSON();
        return( $json->encode($data) );
    }
}


require('../../db_config.php');
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); //defined in db_config.php
mysql_select_db(DB_NAME);

echo '<'.'?xml version="1.0" encoding="utf-8"?'.">\n";

?>
<!DOCTYPE html><!-- XHTML5 -->
<!--
Copyright 2009, OpenScriptures.org
GPL 3 license: http://www.gnu.org/licenses/gpl.html
-->
<html xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml" xmlns:o="http://www.bibletechnologies.net/2003/OSIS/namespace">
	<head>
		<!--[if IE]>
		<meta charset="utf-8" />
		<script>
		//HTML5 enabling script for IE. For discussion and comments, see: http://remysharp.com/2009/01/07/html5-enabling-script/
		(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while (i-=1){document.createElement(e[i])}})()
		</script>
		<![endif]-->
		<title>Work Viewer by Open Scriptures</title>
		<link rel="stylesheet" type="text/css" href="all.css?<?php echo filemtime('all.css') ?>" />
	</head>
	<body>
		<!--[if IE]>
		<p style="background-color:#FFCCCC; padding:1em; border:dotted 1px red; margin-left:auto; margin-right:auto; ">
			<strong>Notice:</strong> This tool may not not function optimally in Internet Explorer. If possible load it in
			<a href="http://www.mozilla.com/firefox/">Mozilla Firefox</a>,
			<a href="http://www.apple.com/safari/">Apple Safari</a>,
			<a href="http://www.opera.com/">Opera</a>,
			or
			<a href="http://www.google.com/chrome">Google Chrome</a> <small>(administrator rights not needed to install Chrome)</small>.
		</p>
		<![endif]-->
		
		<h2><a rel="home" href="/">Open Scriptures</a></h2>
		<h1><?php if(!empty($_SERVER['QUERY_STRING'])): ?><a href='./'><?php endif; ?>Work Viewer<?php if(!empty($_SERVER['QUERY_STRING'])): ?></a><?php endif; ?></h1>
		<noscript>
			<p><em>You should have JavaScript enabled to use this application.</em></p>
		</noscript>
		<form action="./" method="get">
			<?php
			//Get all of the manuscripts in the system
			$workQuery = mysql_query("SELECT id,
			                                 url,
											 type,
											 language,
											 osis_id,
			                                 (SELECT data FROM text WHERE work.name = text.id AND language = 'en') AS name,
			                                 (SELECT data FROM text WHERE work.copyright = text.id AND language = 'en') AS copyright
			                              FROM work
			                              ORDER BY type");
			
			?>
			<!--<p><label for="passage">Passage: </label><select id="passage" name="passage">
				<?php
				//$refQuery = mysql_query("SELECT ref.*, (SELECT data FROM text WHERE ref.name = text.id) as name
				//						  FROM ref, work
				//						  WHERE ref.work = work.id AND work.type = 'unified-manuscript'
				//						  ORDER BY numerical_start");
				//while($ref = mysql_fetch_object($refQuery)){
				//	print "<option value='$ref->osis_id'";
				//	if(@$_REQUEST['book'] == $ref->osis_id)
				//		print " selected='selected'";
				//	print ">$ref->name</option>";
				//}
				?>
			</select></p>-->
			
			<p><label for="workID">Work: </label><select id="workID" name="id"><?php
			$works = array();
			$selectedWork = null;
			$worksByID = array();
			$previousType = '';
			while($work = mysql_fetch_object($workQuery)){
				if($work->id == 1 || $work->id == 3) //German Bible Society wants NA27/UBS4 removed
					continue;
				$worksByID[$work->id] = $work;
				$works[] = &$worksByID[$work->id];
				
				if($previousType != $work->type){
					if($previousType)
						print "</optgroup>";
					print "<optgroup label='$work->type'>";
				}
				
				print "<option value='$work->id'";
				if(@$_REQUEST['id'] == $work->id){
					$selectedWork = &$worksByID[$work->id];
					print ' selected="selected"';
				}
				print ">";
				print $work->name;
				print "</option>";
				
				$previousType = $work->type;
			}
			if($previousType)
				print "</optgroup>";
			?></select></p>
			<p><label for="passage">Passage: </label><input type="text" size="20" name="passage" id="passage" value="<?php
			if(!empty($_REQUEST['passage']))
				echo htmlspecialchars($_REQUEST['passage']);
			else
				echo "1John";
			?>" /> <small>(must be valid osisRef like a single verse <samp>John.3.16</samp>, chapter <samp>Matt.28</samp>, entire book <samp>1John</samp> or a range <samp>Rom.5.5-Rom.5.8</samp>)</small></p>

			<!--<p><input id="include-strongs" name="strongs" value="1" type="checkbox" <?php if(!empty($_GET['strongs']) || empty($_GET)): ?> checked="checked" <?php endif; ?> /><label for="include-strongs">Load Strong's definitions and derivations <small>(increases load time)</small>.</label></p>-->
			<!--
			<p><input disabled="disabled" id="include-punctuation" name="punctuation" value="1" type="checkbox" <?php if(!empty($_GET['punctuation']) || empty($_GET)): ?> checked="checked" <?php endif; ?> /><label for="include-punctuation">Show paragraphs, commas, periods, and other punctuation.</label></p>
			<p><input disabled="disabled" id="include-verse-markers" name="verse-markers" value="1" type="checkbox" <?php if(!empty($_GET['verse-markers']) || empty($_GET)): ?> checked="checked" <?php endif; ?> /><label for="include-verse-markers">Include chapter and verse markers <small>(taken from first <abbr title="manuscript">MS</abbr> above when in unified view)</small>.</label></p>
			Exclude variants (those that appear in brackets)?
			-->
			<p class='buttons'>
				<button type="submit">Display</button>
				<!--<button type="reset">Reset</button>-->
			</p>
		</form>

	<?php
	
	$passage = !empty($_REQUEST['passage']) ? trim($_REQUEST['passage']) : '1John'; #default
	if($selectedWork){
	
	#Parse the osisRef from passage
	@list($osisRefStart, $osisRefEnd) = split('-', $passage, 2);
	function get_edge_token($osis_ref, $start = true){
		global $selectedWork;
		$row = mysql_fetch_row(mysql_query("SELECT token.position FROM token INNER JOIN ref ON token.id = ref." . ($start ? 'start' : 'end') . "_token WHERE token.work = $selectedWork->id AND osis_id = \"" . mysql_real_escape_string($osis_ref) . "\""));
		if($row)
			return $row[0];
		return null;
	}
	
	$startPosition = get_edge_token($osisRefStart);
	if(!$startPosition){
		$osisRefStart = preg_replace('{\..*}', '', $osisRefStart);
		$startPosition = get_edge_token($osisRefStart);
	}
	if($osisRefEnd){
		$endPosition = get_edge_token($osisRefEnd, false);
		if(!$endPosition){
			$osisRefEnd = preg_replace('{\..*}', '', $osisRefEnd);
			$endPosition = get_edge_token($osisRefEnd, false);
		}
	}
	else {
		$endPosition = get_edge_token($osisRefStart, false);
	}
	
	if(!$startPosition || !$endPosition){
		print "<p class='error'><em>Didn't understand the reference \"" . $passage . "\" </em></p>";
	}
	else if($startPosition > $endPosition){
		print "<p class='error'><em>Starting reference is greater than ending reference: \"" . $passage . "\" </em></p>";
	}
	else if($selectedWork){
		?>
		<hr />
		<p id="loadingNotice"><em>Loading...</em></p>
		<?php
		$isTruncated = false;
		if($endPosition-$startPosition > MAX_TOKENS){
			$endPosition = $startPosition+MAX_TOKENS;
			$isTruncated = true;
			print "<p><strong><em>You selected to large of a passage. Your request has been truncated.</em></strong></p>";
		}
		
		$tokenInfo = array();
		
#This single SQL query is used for both the unified and parallel views
$tokenSQL = <<<SQL
SELECT DISTINCT
       token.id AS token_id,
	   token.data AS token_data,
       token.id AS token_id,
	   token.work AS token_work,
       token.data AS token_data,
	   token_parsing.id      AS token_parsing_id,
	   token_parsing.strongs AS token_parsing_strongs,
	   token_parsing.lemma   AS token_parsing_lemma,
	   token_parsing.parse   AS token_parsing_parse,
	   token_parsing.work    AS token_parsing_work,
	   
       ref.type AS ref_type,
	   ref.osis_id AS ref_osis_id,
       /*ref.numerical_start AS ref_numerical_start,*/
       ref_text.data AS ref_name
    FROM  token
      LEFT JOIN token_parsing ON token_parsing.token = token.id
      LEFT JOIN ref ON ref.start_token = token.id AND ref.work = token.work AND ref.type IN ('book','verse')
      LEFT JOIN text AS ref_text ON ref.name = ref_text.id AND ref_text.language = 'en'
    WHERE token.work = $selectedWork->id AND token.position >= $startPosition AND token.position <= $endPosition
    ORDER BY token.position ASC, ref.type ASC
SQL;
		$tokenQueryDuration = microtime(true);
		$tokenQuery = mysql_unbuffered_query($tokenSQL); //mysql_unbuffered_query() can't be used with mysql_data_seek()
		$tokenQueryDuration = microtime(true)-$tokenQueryDuration;
		
		$wordCount = 0;
	
		print "<article id='work'>";
		
		//Print the header, with the individual manuscript names marked up according to which set they appear in
		print "<header><h2>";
		print $selectedWork->name;
		print "</h2></header>";
		
		$parsings = array();
		
		$inParagraph = false;
		$book = $chapter = $verse = 0;
		$bookHTML = '';
		$chapterVerseHTML = '';
		
		#mysql_data_seek($tokenQuery, 0);
		$token = mysql_fetch_object($tokenQuery);
		while($token){
			$id = 't' . $token->token_id;
			if(!isset($tokenInfo[$id]))
				$tokenInfo[$id] = new stdClass();
			
			//Store or output the reference
			switch($token->ref_type){
				case 'book':
					if($inParagraph)
						$bookHTML = "</p><h3>$token->ref_name</h3><p>";
					else
						$bookHTML = "<h3>$token->ref_name</h3>";
					break;
				#case 'chapter':
				#	$chapter = $token->ref_numerical_start;
				#	break;
				case 'verse':
					preg_match('/\.(\d+)\.(\d+)/', $token->ref_osis_id, $matches);
					$chapter = intval($matches[1]);
					$verse = intval($matches[2]);
					#$verse = $token->ref_numerical_start;
					$chapterVerseHTML = "\n<sup o:osisID='$token->ref_osis_id'>$chapter:$verse</sup>";
					break;
			}
			
			//Store parsings
			if(!empty($token->token_parsing_id)){
				$parsing = new stdClass();
				if(!empty($token->token_parsing_lemma))
					$parsing->lemma = $token->token_parsing_lemma;
				if(!empty($token->token_parsing_strongs))
					$parsing->strongs = $token->token_parsing_strongs;
				if(!empty($token->token_parsing_parse))
					$parsing->parse = $token->token_parsing_parse;
				$parsing->work = (int)$token->token_parsing_work;
				$parsings[$token->token_parsing_id] = $parsing;
			}
			
			//If there is no following token or if the next token is different from this one, then print the token
			$nextToken = mysql_fetch_object($tokenQuery);
			if(!$nextToken || $token->token_id != $nextToken->token_id){
				
				print $bookHTML;
				$bookHTML = ''; //reset
				if(!$inParagraph){
					print "<p>";
					$inParagraph = true;
				}
				print $chapterVerseHTML;
				
				$elName = 'span';
				
				if(!empty($parsings))
					$tokenInfo[$id]->p = array_values($parsings);
				
				$chapterVerseHTML = ''; //reset
				#print "<$elName id='t{$id}'>";
				print $token->token_data;
				$wordCount++;
				#print "</$elName>";
				
				print ' ';
				
				$parsings = array(); //reset
			}
			$token = $nextToken;
		}
		if($inParagraph)
			print "</p>";
			
			
		if($isTruncated)
			print "<p><strong><em>You selected to large of a passage. Your request has been truncated.</em></strong></p>";
		print "<footer><p>Word count: $wordCount</p></footer>";
		print "<hr />";
		#print "<footer>";
		#print "Words inserted: $insUniqueWordCount. Words deleted: $delUniqueWordCount.";
		#print "</footer>";
		
		$license = mysql_fetch_object(mysql_query("SELECT *, (SELECT data FROM text WHERE license.name = text.id AND language = 'en') AS name FROM license INNER JOIN work_license ON license.id = work_license.license WHERE work_license.work = $selectedWork->id"));
		print '<footer>';
		print "<address><cite>" . $selectedWork->name . "</cite>: " . $selectedWork->copyright . "</address>";
		print "<p>License: ";
		if(!$license)
			print "<em>(Unknown</em>)";
		else
			print "<a rel='license' href='" . htmlspecialchars($license->url) . "'>" . htmlspecialchars($license->name) . "</a>";
		print "</p>";
		if($selectedWork->url){
			print "<p>Source: <a href='" . htmlspecialchars($selectedWork->url) . "'>" . htmlspecialchars(basename($selectedWork->url)) . "</a>";
			$domain = parse_url($selectedWork->url, PHP_URL_HOST);
			print " @ <a href='" . parse_url($selectedWork->url, PHP_URL_SCHEME) .  "://$domain'>$domain</a></p>";
		}
		print "</footer>";

		print '</article>';
		

		print "\n<!--\n";
		#print "Total rows: " . mysql_num_rows($tokenQuery) . "\n";
		print "Query time: $tokenQueryDuration secs\n";
		print "Script time: " . ((microtime(true) - $startTime) - $tokenQueryDuration) . " secs\n";
		print "-->\n";

		print "\n";
		print "\t\t<script>/*<![CDATA[*/\n";
		print "\t\t//p=parsings, w=uniqueTokenWorks, u=tokenFromUMS\n";
		$js = "\t\tvar tokenInfo = " . json_encode($tokenInfo) . ";\n";
		print html_entity_decode(preg_replace('/\\\\u([0-9a-f][0-9a-f][0-9a-f][0-9a-f])/', '&#x$1;', $js), ENT_NOQUOTES, 'UTF-8'); #Convert escaped Unicode to UTF-8 to compact file size
		print "\t\t//]]></script>\n";
		
		//Output all of the tokenParsings
		if(!empty($_REQUEST['strongs'])){
			print "\t\t<script src='../strongs-greek-dictionary.js?" . filemtime('../strongs-greek-dictionary.js') . "'></script>";
		}
	}
	} //end if valid request?>

		<hr />
		<footer>
			<address>
				Copyright 2009, <a href="http://openscriptures.org/" rel="home">OpenScriptures.org</a>. 
			</address>
			<p>
				Code open source under <a href="http://www.gnu.org/licenses/gpl.html" rel="license">GPL 3</a>.
				<!--Derivative content and contributor -->Content licensed <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-Noncommercial-Share Alike 3.0</a> if permitted by supporting works.
				<span class="host">Hosted by <a href="http://shepherd-interactive.com/">Shepherd Interactive</a>.</span>
			</p>
			<p class='repo'><?php print format_svn_id('$Id: index.php 214 2009-05-18 02:29:25Z WestonRuter@gmail.com $', '$URL: http://open-scriptures.googlecode.com/svn/tags/0.1/web/prototypes/work-viewer/index.php $'); ?></p>
		</footer>
	
		<?php if(file_exists('../jquery.min.js')): ?>
		<script src="../jquery.min.js?ver=1.3.1"></script>
		<?php else: ?>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
		<?php endif; ?>
		<script src="../jquery-ui-personalized-1.6rc6.min.js"></script>
		<!--<script src="../jquery.cookie.js"></script>-->
		<script src="main.js?<?php echo filemtime('main.js') ?>"></script>
		
		<!-- Google Analytics -->
		<script src="http://www.google-analytics.com/ga.js"></script>
		<script type="text/javascript">
		try {
			var pageTracker = _gat._getTracker("UA-6816157-1");
			pageTracker._trackPageview();
		} catch(e) {}
		</script>
	</body>
</html>